﻿using _1._13._2015_Art.Data;
using _1._13._2015_Art.Data.Models;
using _1._13._2015_Art.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace _1._13._2015_Art.Controllers
{
    public class ArtistController : ApiController
    {
        public IHttpActionResult Get()
        {
            List<ArtistViewModel> models = null;
            using(ApplicationDbContext db = new ApplicationDbContext())
            {
                UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
                UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

                models = db.Users.Select(u => new ArtistViewModel
                {
                    ArtistId = u.Id,
                    FirstName = u.FirstName,
                    LastName = u.LastName,
                    Bio = u.Bio,
                    
                }).ToList();
                foreach (var a in models)
                {
                    a.IsAdmin = userManager.IsInRole(a.ArtistId, "Admin");
                     
                    if(User.Identity.GetUserId() == a.ArtistId)
                    {
                        a.LoggedIn = true;
                    }
                }
            }
           return Ok(models);
        }
        [Authorize(Roles = "Admin")]
        // add new artist
        public IHttpActionResult Post(ArtistViewModel model)
        {

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
                UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

                RoleStore<Role> roleStore = new RoleStore<Role>(db);
                RoleManager<Role> roleManager = new RoleManager<Role>(roleStore);

                ApplicationUser artist = new ApplicationUser{
                     Bio = model.Bio,
                     FirstName = model.FirstName,
                     LastName = model.LastName,
                     Email = model.Email,
                     UserName = model.Email,
                     
                };
                userManager.Create(artist, "123456");
                userManager.AddToRole(artist.Id, model.Role);
                                
                db.SaveChanges();
            }
            return Ok();
        }

    }
}

